package com.bilibili.server.controller;

import com.bilibili.server.dto.AuthResponse;
import com.bilibili.server.dto.ChangePasswordRequest;
import com.bilibili.server.dto.LoginRequest;
import com.bilibili.server.dto.RegisterRequest;
import com.bilibili.server.dto.Response;
import com.bilibili.server.entity.User;
import com.bilibili.server.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/auth")
public class AuthController {
    @Autowired
    private AuthService authService;

    // 用户注册接口
    @PostMapping("/register")
    public ResponseEntity<Response<AuthResponse>> register(@RequestBody RegisterRequest registerRequest) {
        try {
            AuthResponse authResponse = authService.register(registerRequest);
            return new ResponseEntity<>(Response.created("注册成功", authResponse), HttpStatus.CREATED);
        } catch (RuntimeException e) {
            return new ResponseEntity<>(Response.error(400, e.getMessage()), HttpStatus.BAD_REQUEST);
        } catch (Exception e) {
            return new ResponseEntity<>(Response.error(500, "服务器内部错误"), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    // 用户登录接口
    @PostMapping("/login")
    public ResponseEntity<Response<AuthResponse>> login(@RequestBody LoginRequest loginRequest) {
        try {
            if (loginRequest.getUsername() == null || loginRequest.getPassword() == null) {
                return new ResponseEntity<>(Response.error(400, "用户名和密码不能为空"), HttpStatus.BAD_REQUEST);
            }

            AuthResponse authResponse = authService.login(loginRequest.getUsername(), loginRequest.getPassword());
            return new ResponseEntity<>(Response.success("登录成功", authResponse), HttpStatus.OK);
        } catch (RuntimeException e) {
            return new ResponseEntity<>(Response.error(401, "用户名或密码错误"), HttpStatus.UNAUTHORIZED);
        } catch (Exception e) {
            return new ResponseEntity<>(Response.error(500, "服务器内部错误"), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    // 获取用户信息接口
    @GetMapping("/profile")
    public ResponseEntity<Response<User>> getProfile() {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();

            User user = authService.getCurrentUser(username);
            return new ResponseEntity<>(Response.success("获取成功", user), HttpStatus.OK);
        } catch (RuntimeException e) {
            return new ResponseEntity<>(Response.error(401, "Token无效或已过期"), HttpStatus.UNAUTHORIZED);
        } catch (Exception e) {
            return new ResponseEntity<>(Response.error(500, "服务器内部错误"), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    // 修改密码接口
    @PutMapping("/change-password")
    public ResponseEntity<Response<Void>> changePassword(@RequestBody ChangePasswordRequest changePasswordRequest) {
        try {
            if (changePasswordRequest.getOldPassword() == null || changePasswordRequest.getNewPassword() == null) {
                return new ResponseEntity<>(Response.error(400, "旧密码和新密码不能为空"), HttpStatus.BAD_REQUEST);
            }

            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();

            authService.changePassword(username, changePasswordRequest.getOldPassword(), changePasswordRequest.getNewPassword());
            return new ResponseEntity<>(Response.success("密码修改成功"), HttpStatus.OK);
        } catch (RuntimeException e) {
            if ("旧密码错误".equals(e.getMessage())) {
                return new ResponseEntity<>(Response.error(400, e.getMessage()), HttpStatus.BAD_REQUEST);
            } else {
                return new ResponseEntity<>(Response.error(401, "Token无效或已过期"), HttpStatus.UNAUTHORIZED);
            }
        } catch (Exception e) {
            return new ResponseEntity<>(Response.error(500, "服务器内部错误"), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}